package cn.ug.account.service.impl;

import cn.ug.account.bean.AreaBean;
import cn.ug.account.mapper.AreaMapper;
import cn.ug.account.mapper.entity.Area;
import cn.ug.account.service.AreaService;
import cn.ug.aop.SaveCache;
import cn.ug.config.Config;
import cn.ug.config.RedisGlobalLock;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.UF;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static cn.ug.config.CacheType.OBJECT;

/**
 * @author kaiwotech
 */
@Service
public class AreaServiceImpl extends BaseServiceImpl implements AreaService {

    @Resource
    private AreaMapper areaMapper;

    @Resource
    private Config config;

    @Resource
    private DozerBeanMapper dozerBeanMapper;

    @Resource
    private RedisGlobalLock redisGlobalLock;

    @Override
    @SaveCache(cacheType = OBJECT)
    public AreaBean findById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }

        Area entity = areaMapper.findById(id);
        if (null == entity) {
            return null;
        }

        AreaBean entityBean = dozerBeanMapper.map(entity, AreaBean.class);
        entityBean.setAddTimeString(UF.getFormatDateTime(entity.getAddTime()));
        entityBean.setModifyTimeString(UF.getFormatDateTime(entity.getModifyTime()));
        return entityBean;
    }

    @Override
    public List<AreaBean> findList(String order, String sort, String cityCode, String parentId) {
        List<AreaBean> dataList = new ArrayList<>();
        List<Area> list = areaMapper.query(
                getParams(null, order, sort)
                        .put("cityCode", cityCode)
                        .put("parentId", parentId)
                        .toMap());
        for (Area o : list) {
            AreaBean objBean = dozerBeanMapper.map(o, AreaBean.class);
            objBean.setAddTimeString(UF.getFormatDateTime(o.getAddTime()));
            objBean.setModifyTimeString(UF.getFormatDateTime(o.getModifyTime()));
            dataList.add(objBean);
        }
        return dataList;
    }

}

